package com.jf.mall.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-10-11
 * Time:20:20
 */
@WebFilter(urlPatterns = "/views/admin/*",
        servletNames = "FurnitureServlet",
        initParams = {@WebInitParam(name = "excludeUrl", value = "/views/admin/admin_login.jsp")})
public class AdminFilter implements Filter {
    private List<String> excludeUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludeUrl = filterConfig.getInitParameter("excludeUrl");
        if (excludeUrl != null) {
            String[] split = excludeUrl.split(",");
            excludeUrls = Arrays.asList(split);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object admin = request.getSession().getAttribute("admin");
        String url = request.getServletPath();
        if (admin == null) {
            if (excludeUrls.contains(url)) {
                filterChain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
            return;
        } else {
            if (excludeUrls.contains(url)) {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                filterChain.doFilter(request, response);
            }
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
